package com.file.module.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class CalAr {
    public static Double calculate(String url) {
        double width = 0;
        double height = 0;
        double ar = 0;

        Pattern pattern = Pattern.compile("_(\\d+)x(\\d+)\\.");
        Matcher matcher = pattern.matcher(url);

        if (matcher.find()) {//如果url可以匹配
            width = Double.parseDouble(matcher.group(1));
            height = Double.parseDouble(matcher.group(2));
            if (width == 0 || height == 0) {//如果宽或高为0则去url拉取图片
                log.info("图片宽或高为0");
                BufferedImage image;
                try {
                    image = ImageIO.read(new URL(url));
                } catch (IOException e) {
                    log.info("拉取图片失败");//如果拉取图片失败，将ar设置为0
                    return ar = 0;
                }
                if (image != null) {
                    log.info("拉取图片成功，重新设定宽高");//拉取成功,重新设置宽高
                    width = image.getWidth();
                    height = image.getHeight();
                }
            }
        } else {//如果url无法匹配
            log.info("无法通过url获取宽高");
            BufferedImage image = null;
            try {
                image = ImageIO.read(new URL(url));
            } catch (IOException e) {
                log.info("拉取图片失败");//如果拉取图片失败，将ar设置为0
                return ar = 0;
            }
            if (image != null) {
                log.info("拉取图片成功，重新设定宽高");//拉取成功
                width = image.getWidth();
                height = image.getHeight();
            }
        }
        ar = width / height;
        return ar;
    }
}
